<template>
  <view class="login-wrap custom-uni-view">
    <view class="top-text">
      <text @click="toJoin">加盟入驻</text>
      <span></span>
    </view>
    <view class="common-tab-x tab p90">
      <view class="common-tab-text" :class="{active: !isAccount}" @tap="changeLogin" >验证码登录</view>
      <view class="common-tab-text" :class="{active: isAccount}" @tap="changeLogin" >密码登陆</view>
    </view>
    <view class="h20"></view>
    
    <!-- 验证码登录 -->
    <view class="code p90" v-if="!isAccount">
      <view class="box" :class="{active: !isAct}">
        <view class="label">手机号</view>
        <view class="inpt">
          <input class="input" type="number" v-model="phone" maxlength="11" placeholder="请输入手机号" @focus="getActive(0)">
        </view>
      </view>
      <view class="box" :class="{active: isAct}">
        <view class="label code">验证码</view>
        <view class="inpt">
          <input type="number" class="input" maxlength="6" @focus="getActive(1)" placeholder="请输入验证码" v-model="code">
        </view>
        <view class="line">
          <span @click="getCode" v-if="!timer">获取验证码</span>
          <span v-else>重发{{count}}s</span>
        </view>
      </view>
      <button type="primary" class="sub-btn" @click="loginByCode">登录</button>
      <view class="hint">未注册的手机号也将自动创建社区电商账号</view>
    </view>
    <!--  -->
    
    <!-- 密码登录 -->
    <view class="code p90" v-else>
      <view class="box" :class="{active: !isAct}">
        <view class="label">账号</view>
        <view class="inpt"><input class="input" type="text" @focus="getActive(0)" v-model="phone"  placeholder="请输入账号"></view>
      </view>
      
      <view class="box" :class="{active: isAct}">
        <view class="label">密码</view>
        <view class="inpt"><input type="password" @focus="getActive(1)" placeholder="请输入密码" class="input" v-model="password"></view>
        <view class="line" @click="gotoForget">
          <span>忘记密码</span>
        </view>
      </view>
      <button type="primary" class="sub-btn" @click="loginByPassword">登录</button>
      <view class="hint" style="height: 32rpx;"> </view>
    </view>
    <!--  -->
    <view class="version">
      version：2.0.0.191122_beta_j
    </view>
    <!-- 其他方式登录 -->
    <view class="footer p90" style="margin-top: 80rpx;"  v-if="decideEnv || hasProvider">
      <view class="f-t" >
        <span class="other-login-way">其他方式登录</span>
      </view>
      <block v-if="decideEnv">
        <view class="icon" v-if="decideEnv == 'wx'">
          <image :src="$store.state.imgBaseUrl + '/login/wx_icon.png'" @tap="oauth_weixin()" class="weixin_img"></image>
        </view>
        <!-- <view class="icon" v-if="decideEnv == 'zfb'">
          <image :src="$store.state.imgBaseUrl + '/login/pay_icon.png'" @tap="oauth_alipay()" class="weixin_img"></image>
        </view> -->
      </block>
      <block v-if="hasProvider">
        <view class="oauth-row" v-if="hasProvider" v-bind:style="{top: positionTop + 'px'}">
          <view class="oauth-image" v-for="provider in providerList" :key="provider.value">
            <image :src="provider.image" @tap="oauth(provider.value)"></image>
          </view>
        </view>
      </block>
    </view>
    <!--  -->
    
    <view class="agree">
      <radio :value="isCheck" :checked="isCheck == '1'" @tap="isAgree" class="agree-radio" color="#C2AC78"/>
      <text class="agree-text-1">登录即代表您已同意<text class="agree-text-2">《登录注册协议》</text></text>
    </view>
  
  </view>
</template>

<script>
// import $wx from '../../unit/authorization.js';
import md5 from 'js-md5';
import qs from 'qs';
import { decideEnv, getUrlParam } from '@/unit/common.js';
import { SendCode, CheckCode } from '@/service/common/code.service.js'
import { wxAuthorization, wxAuthorizationLogin, loginByPassword, loginByCode, getAlipayAuthLoginApi, loginInAlipayApi } from '@/service/login/login.service.js'

export default {
  data() {
    return {
      loginCode: null,
      from: null,
      isAccount: false,
      mobile: '', // 账号密码登录手机号
      phone: '', // 验证码登录手机号
      password: '', // 密码
      code: '', // 验证码
      hasProvider: false,
      positionTop: 0,
      providerList: [],
      // wx: $wx,
      decideEnv: null, // 当前环境 ，目前判断微信公众号 和 支付宝
      isAct: false,
      loginText: '微信登录',
      isCheck: '1', // 是否同意登录注册协议 0：不同意 1：同意
      count: 60, // 倒计时秒数
      timer: null,
      inviteId: ''
    }
  },
  created () {
    this.decideEnv = decideEnv();
    // if (getUrlParam('code')) {
    //   this.wxLogin();
    // }
  },
  methods: {
    toJoin () { // 加盟入驻
      try {
        let token = uni.getStorageSync('user_token');
        if (!token) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })
        } else {
          uni.navigateTo({
            url: '/pages/join/result'
          })
        }
      } catch(e) {
        //TODO handle the exception
      }
    },
    isAgree () {
      this.isCheck = this.isCheck == '0' ? '1' : '0'
    },
    wxLogin () { // 通过code码拿取用户信息
      let params = Object.assign({code: this.loginCode});
      let inviteId = uni.getStorageSync('userInvite')
      if (inviteId) {
        params.inviteId = inviteId;
      }
      wxAuthorization(params, (res) => {
        if (res.status == 0 && !res.data.token) {
          uni.navigateTo({
            url: '/pages/login/bindPhone?openId=' + res.data.openId + '&unionId=' + res.data.unionId
          })
        } else if (res.status == 0 && res.data.token) {
          uni.removeStorageSync('userInvite');
          uni.setStorageSync('freeStore', res.data.freeStore);
          uni.showToast({
            title: '登陆成功！',
            duration: 2000,
            success: () => {
              uni.setStorage({
                key: 'user_token',
                data: res.data.token,
                success: () => {
                  if (res.data.rank < 2 && res.data.freeStore == 0) {
                    setTimeout(() => {
                      uni.reLaunch({
                        url: '/pages/join/result'
                      })
                    }, 2000);
                  } else if (res.data.rank < 2 && res.data.freeStore == 1) {
                    setTimeout(() => {
                      uni.reLaunch({
                        url: '/pages/freeStore/result'
                      })
                    }, 2000);
                  } else {
                    this.$store.dispatch('getUserInfo').then(res => {
                      setTimeout(() => {
                        if (this.from) {
                          // #ifdef H5
                          window.open(decodeURIComponent(this.from), '_self');
                          // #endif
                        } else {
                          uni.switchTab({
                            url: '/pages/index/index'
                          })
                        }
                      }, 1500)
                    });
                  }
                }
              });
            }
          });
        } else if (res.status == 0 && res.data.rank < 2) {
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/join/result'
            })
          }, 2000)
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          });
        }
      });
    },
    loginInAlipay () {
      loginInAlipayApi({code: this.loginCode}, (res) => {
        if (res.status == 0 && !res.data.token) {
          uni.navigateTo({
            url: '/pages/login/bindPhone?alipayUserId=' + res.data.alipayUserId 
          })
        } else if (res.status == 0 && res.data.token) {
          uni.setStorageSync('freeStore', res.data.freeStore);
          uni.showToast({
            title: '登陆成功！',
            duration: 2000,
            success: () => {
              uni.setStorage({
                key: 'user_token',
                data: res.data.token,
                success: () => {
                  if (res.data.rank < 2 && res.data.freeStore == 0) {
                    setTimeout(() => {
                      uni.reLaunch({
                        url: '/pages/join/result'
                      })
                    }, 2000);
                  } else if (res.data.rank < 2 && res.data.freeStore == 1) {
                    setTimeout(() => {
                      uni.reLaunch({
                        url: '/pages/freeStore/result'
                      })
                    }, 2000);
                  } else {
                    this.$store.dispatch('getUserInfo').then(res => {
                      setTimeout(() => {
                        if (this.from) {
                          // #ifdef H5
                          window.open(decodeURIComponent(this.from), '_self');
                          // #endif
                        } else {
                          uni.switchTab({
                            url: '/pages/index/index'
                          })
                        }
                      }, 1500)
                    });
                  }
                }
              });
            }
          });
        } else if (res.status == 0 && res.data.rank < 2) {
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/join/result'
            })
          }, 2000)
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          });
        }
      });
    },
    oauth_weixin () { // 微信公众号授权登录
      wxAuthorizationLogin({}, (res) => {
        if (res.status == 0) {
          // #ifdef H5
          window.location.href = res.data.url;
          // #endif
        }
      });
    },
    oauth_alipay () { // 获取支付宝授权登录地址
      getAlipayAuthLoginApi({}, res => {
        if (res.status == 0) {
          // #ifdef H5
          window.location.href = res.data.url;
          // #endif
        }
      }, null, {showErrorMsg: true});
    },
    loginByPassword () { // 密码登录
      if (!this.phone) {
        uni.showToast({
          title: '请输入账号',
          icon: 'none'
        });
        return false;
      } else if (!this.password) {
        uni.showToast({
          title: '请输入密码',
          icon: 'none'
        });
        return false;
      } else if (this.isCheck == '0') {
        uni.showToast({
          title: '请阅读登录协议并同意',
          icon: 'none'
        });
        return false;
      } else {
        let params = Object.assign({
          mobile: this.phone,
          password: md5(this.password, 32)
        });
        let inviteId = uni.getStorageSync('userInvite')
        if (inviteId) {
          params.inviteId = inviteId;
        }
        loginByPassword(params, (res) => {
          if (res.status == 0) {
            uni.removeStorageSync('userInvite');
            uni.setStorageSync('freeStore', res.data.freeStore);
            uni.showToast({
              title: '登陆成功！',
              duration: 2000,
              success: () => {
                uni.setStorage({
                  key: 'user_token',
                  data: res.data.token,
                  success: () => {
                    if (res.data.rank < 2 && res.data.freeStore == 0) {
                      setTimeout(() => {
                        uni.reLaunch({
                          url: '/pages/join/result'
                        })
                      }, 2000);
                    }else if (res.data.rank < 2 && res.data.freeStore == 1) {
                      setTimeout(() => {
                        uni.reLaunch({
                          url: '/pages/freeStore/result'
                        })
                      }, 2000);
                    } else {
                      this.$store.dispatch('getUserInfo').then(res => {
                        setTimeout(() => {
                          if (this.from) {
                            // #ifdef H5
                            window.open(decodeURIComponent(this.from), '_self');
                            // #endif
                          } else {
                            uni.switchTab({
                              url: '/pages/index/index'
                            })
                          }
                        }, 1500)
                      });
                    }
                  }
                });
              }
            })
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        });
      }
    },
    loginByCode () { // 验证码登录
      let reg = /^1[0-9]{10,10}$/;
      if (!this.phone) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        });
        return false;
      } else if (!reg.test(this.phone)) {
        uni.showToast({
          title: '手机号码有误，请重新输入',
          icon: 'none'
        });
        return false;
      } else if (!this.code) {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none'
        });
        return false;
      } else if (this.isCheck == '0') {
        uni.showToast({
          title: '请阅读登录协议并同意',
          icon: 'none'
        });
        return false;
      } else {
        let params = Object.assign({ mobile: this.phone, code: this.code, type: 0});
        let inviteId = uni.getStorageSync('userInvite')
        if (inviteId) {
          params.inviteId = inviteId;
        }
        loginByCode(params, (res) => {
          if (res.status == 0) {
            uni.removeStorageSync('userInvite');
            uni.setStorageSync('freeStore', res.data.freeStore);
            uni.showToast({
              title: '登陆成功！',
              duration: 2000,
              success: () => {
                uni.setStorage({
                  key: 'user_token',
                  data: res.data.token,
                  success: () => {
                    if (res.data.rank < 2 && res.data.freeStore == 0) {
                      setTimeout(() => {
                        uni.reLaunch({
                          url: '/pages/join/result'
                        })
                      }, 2000);
                    }else if (res.data.rank < 2 && res.data.freeStore == 1) {
                      setTimeout(() => {
                        uni.reLaunch({
                          url: '/pages/freeStore/result'
                        })
                      }, 2000);
                    } else {
                      this.$store.dispatch('getUserInfo').then(res => {
                        setTimeout(() => {
                          if (this.from) {
                            // #ifdef H5
                            window.open(decodeURIComponent(this.from), '_self');
                            // #endif
                          } else {
                            uni.switchTab({
                              url: '/pages/index/index'
                            })
                          }
                        }, 1500)
                      });
                    }
                  }
                });
              }
            })
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        });
      }
    },
    gotoForget () { // 
      uni.navigateTo({
        url: '/pages/login/forgetPw' + (this.from ? '?from=' + this.from : '')
      });
    },
    getAgreement () {
      this.isCheck = !this.isCheck;
    },
    getActive (index) {
      index == 0 ? this.isAct = false : this.isAct = true;
    },
    changeLogin () {
      this.isAccount = !this.isAccount;
      
    },
    async getCode () {
      let reg = /^1[0-9]{10,10}$/;
      if (!this.phone) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        });
        return false;
      } else if (!reg.test(this.phone)) {
        uni.showToast({
          title: '手机号码有误，请重新输入',
          icon: 'none'
        });
        return false;
      } else {
        SendCode({ mobile: this.phone, type: 0}, (res) => {
          if (res.status == 0) {
            uni.showToast({
              title: '验证码发送成功！',
              icon: 'none'
            });
            this.countDown();
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            });
          }
        });
      }
    },
    countDown () {
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000)
      }
    },
    oauth(value) {
      let _t = this;
      uni.login({
        provider: value,
        success: (res) => {
          uni.getUserInfo({
            provider: value,
            success: (infoRes) => {
              /**
               * 实际开发中，获取用户信息后，需要将信息上报至服务端。
               * 服务端可以用 userInfo.openId 作为用户的唯一标识新增或绑定用户信息。
               */ 
              // _t.toMain(infoRes.userInfo);
            }
          });
        },
        fail: (err) => {
          console.error('授权登录失败：' + JSON.stringify(err));
        }
      });
    },
    toMain(data) {
      /**
       * 强制登录时使用reLaunch方式跳转过来
       * 返回首页也使用reLaunch方式
       */
      this.$store.commit('getUserInfo', data);
      this.reLaunch({
        url: '/pages/index/index'
      })
    },
    initPosition() {
      /**
         * 使用 absolute 定位，并且设置 bottom 值进行定位。软键盘弹出时，底部会因为窗口变化而被顶上来。
         * 反向使用 top 进行定位，可以避免此问题。
         */
      this.positionTop = uni.getSystemInfoSync().windowHeight - 100;
    },
    initProvider() {
      const filters = ['weixin'];
      let _t = this;
      uni.getProvider({
        service: 'oauth',
        success: function (res) {
          if (res.provider && res.provider.length) {
            for (let i = 0; i < res.provider.length; i++) {
              if (~filters.indexOf(res.provider[i])) {
                _t.providerList.push({
                  value: res.provider[i],
                  image: '/static/image/' + res.provider[i] + '.png'
                })
              }
            }
            _t.hasProvider = true;
          }
        }
      });
    }
  },
  onReady() {
    // uni.clearStorageSync();
    this.initPosition();
    this.initProvider();
  },
  onLoad (option) { //option为object类型，会序列化上个页面传递的参数
    this.from = option.from;
    this.loginCode = option.code || option.auth_code;
    if (option.inviteId) {
      this.inviteId = option.inviteId;
      uni.setStorage({
        key: 'userInvite',
        data: option.inviteId
      })
    }
    if (option.code && decideEnv() && decideEnv() == 'wx') {
      this.wxLogin();
    }
    // else if (option.auth_code && decideEnv() && decideEnv() == 'zfb') {
    //   this.loginInAlipay();
    // }
  }
}
</script>

<style scoped lang="scss">
  .p90 {
    padding: 0 90rpx;
  }
  .h20 {
    width: 100%;
    height: 20rpx;
    background-color: #FAFAFA;
    margin-top: 15rpx;
  }
  .version {
    text-align: center;
    font-size: 30rpx;
    color: #999999;
    font-weight: 500;
    margin-top: 60rpx;
  }
  .oauth-row {
    display: flex;
    flex-direction: row;
    justify-content: center;
    width: 100%;
    margin-top: 60rpx;
    .oauth-image {
        width: 80rpx;
        height: 80rpx;
        border: 1rpx solid #dddddd;
        border-radius: 100rpx;
        margin: 0 40rpx;
        background-color: #ffffff;
        image {
          width: 80rpx;
          height: 80rpx;
          // margin: 20rpx;
        }
    }
  }
  .login-wrap {
    height: 100vh;
    color: #333333;
    background-color: #FFFFFF;
    // padding-top: 20rpx;
    .top-text {
      padding-top: 20rpx;
      text-align: right;
      padding-right: 30rpx;
      font-size: 36rpx;
      color: #666666;
      font-weight: bold;
      font-style: italic;
      position: relative;
      margin-bottom: 90rpx;
      span {
        display: bold;
        width: 36rpx;
        height: 36rpx;
        border-radius: 50%;
        background-color: #434343;
        opacity: 0.17;
        position: absolute;
        right: 18rpx;
        bottom: -5rpx;
      }
    }
    .common-tab-x {
      font-size: 28rpx;
      color: #333333;
      .common-tab-text {
        padding: 0 5rpx;
        font-size: 36rpx;
        color: #999999;
        margin-right: 92rpx;
        display: inline-block;
        &.active {
          color: #333333;
          font-weight: bold;
          &:after {
            content: '';
            height: 3rpx;
            opacity: 1;
            background-color: #F6DA99;
            bottom: -15rpx;
          }
        }
      }
    }
    .code {
      .box {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding: 30rpx 0;
        font-size: 28rpx;
        border-bottom: 1rpx solid #E1E1E1;
        &.active {
          border-color: #F6DA99;
        }
        .name {
          width: 82rpx;
          font-size: 28rpx;
        }
       
        .inpt {
          // width: 320rpx;
          flex: 1;
          margin-left: 40rpx;
          input {
            font-size: 28rpx;
            font-weight:500;
          }
        }
        .label {
          width: 90rpx;
          font-size: 28rpx;
          color: #333333;
          font-weight:500;
        }
        .line {
          // flex: 1;
          // width: 120rpx;
          font-size: 24rpx;
          text-align: right;
        }
      }
      .sub-btn {
        margin-top: 112rpx;
        height: 70rpx;
        line-height: 70rpx;
        background-color: #434343;
        border-radius: 10rpx;
        color: #F6DA99;
        font-size: 30rpx;
        // text-align: center;
        &.active {
          background-color: #434343;
          color: #F6DA99;
        }
      }
      .hint {
        text-align: center;
        font-size: 24rpx;
        color: #999999;
        margin-top: 17rpx;
      }
    }
    .footer {
      margin-top: 150rpx;
      font-size: 24rpx;
      .f-t {
        position: relative;
        span {
          color: #999999;
          margin: 11px 0;
          line-height: 2rpx;
          border-left: 185rpx solid #999999;
          border-right: 185rpx solid #999999;
          text-align: center;
          display: block;
        }
      }
      .icon {
        padding-top: 60rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #636363;
        .weixin_img {
          width: 80rpx;
          height: 80rpx;
          background-color: #CCCCCC;
          border-radius: 50%;
        }
      }
    }
    .agree {
      margin: 88rpx 0 0;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #999999;
      font-size: 24rpx;
      .agree-radio {
        // width: 30rpx;
        // height: 30rpx;
        .uni-radio-input {
          width: 100%;
          height: 100%;
        }
        .uni-radio-input-checked {
          
        }
      }
      .agree-text-1 {
        margin-left: 22rpx;
        color: #999999;
      }
      .agree-text-2 {
        color: #C2AC78;
      }
    }
  }
</style>

